package com.example.broadcastreceiverdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BatteryReceiver receiver=new BatteryReceiver();


        Button bt1 =(Button) findViewById(R.id.button);
        Button bt2 =(Button) findViewById(R.id.button2);
        bt1.setOnClickListener((v)->{
            Intent intent = new Intent(this, MainActivity2.class);
            Bundle bundle = new Bundle();
            bundle.putString("key","hello");
            intent.putExtras(bundle);
            startActivity(intent);
        });
        bt2.setOnClickListener((v)->{
          /*  Intent zsIntent = new Intent("zs");
            Bundle bundle = new Bundle();
            bundle.putString("key1","hello1");
            zsIntent.putExtras(bundle);*/
            IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
            registerReceiver(receiver,filter);
        });
    }
    public class BatteryReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            TextView tv1 =(TextView) findViewById(R.id.textview);
            if(action.equals(Intent.ACTION_BATTERY_CHANGED)){
                int current=intent.getExtras().getInt("level");
                int total=intent.getExtras().getInt("scale");
                int percent=current*100/total;
                tv1.setText(percent+"%");
            }
        }
    }
}